<!-- 资源占用监控组件 -->
<template>
  <div class="resource-monitor">
    <div class="monitor-header">
      <h3 class="monitor-title">
        <el-icon><Monitor /></el-icon>
        资源占用监控
      </h3>
      <div class="monitor-controls">
        <el-select v-model="timeRange" size="small" style="width: 8vw;">
          <el-option label="1分钟" value="1m" />
          <el-option label="5分钟" value="5m" />
          <el-option label="15分钟" value="15m" />
          <el-option label="1小时" value="1h" />
        </el-select>
        <el-button size="small" @click="toggleRealtime" :type="isRealtime ? 'primary' : ''">
          <el-icon><VideoPlay /></el-icon>
          {{ isRealtime ? '暂停' : '实时' }}
        </el-button>
      </div>
    </div>

    <div class="monitor-content">
      <!-- 系统概览 -->
      <div class="system-overview">
        <div class="overview-card">
          <div class="card-icon cpu">
            <el-icon><Odometer /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ cpuUsage }}%</div>
            <div class="card-label">CPU使用率</div>
          </div>
          <div class="card-trend" :class="cpuTrend">
            <el-icon><component :is="cpuTrendIcon" /></el-icon>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-icon memory">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ memoryUsage }}%</div>
            <div class="card-label">内存使用率</div>
          </div>
          <div class="card-trend" :class="memoryTrend">
            <el-icon><component :is="memoryTrendIcon" /></el-icon>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-icon disk">
            <el-icon><FolderOpened /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ diskUsage }}%</div>
            <div class="card-label">磁盘使用率</div>
          </div>
          <div class="card-trend" :class="diskTrend">
            <el-icon><component :is="diskTrendIcon" /></el-icon>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-icon network">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-value">{{ networkSpeed }}</div>
            <div class="card-label">网络速度</div>
          </div>
          <div class="card-trend" :class="networkTrend">
            <el-icon><component :is="networkTrendIcon" /></el-icon>
          </div>
        </div>
      </div>

      <!-- 实时图表 -->
      <div class="charts-container">
        <div class="chart-panel">
          <div class="chart-header">
            <span>CPU使用率曲线</span>
            <span class="chart-value">当前: {{ cpuUsage }}%</span>
          </div>
          <div ref="cpuChartRef" class="chart-content"></div>
        </div>

        <div class="chart-panel">
          <div class="chart-header">
            <span>内存使用率曲线</span>
            <span class="chart-value">当前: {{ memoryUsage }}%</span>
          </div>
          <div ref="memoryChartRef" class="chart-content"></div>
        </div>
      </div>

      <!-- 进程列表 -->
      <div class="process-list">
        <div class="list-header">
          <span>资源占用进程 TOP 10</span>
          <el-button size="small" text @click="refreshProcesses">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="list-content">
          <div class="process-header">
            <span class="col-name">进程名称</span>
            <span class="col-cpu">CPU %</span>
            <span class="col-memory">内存 %</span>
            <span class="col-status">状态</span>
          </div>
          <div class="process-item" v-for="process in processes" :key="process.id">
            <span class="col-name">{{ process.name }}</span>
            <span class="col-cpu">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: process.cpu + '%' }"></div>
                <span class="progress-text">{{ process.cpu }}%</span>
              </div>
            </span>
            <span class="col-memory">
              <div class="progress-bar">
                <div class="progress-fill memory" :style="{ width: process.memory + '%' }"></div>
                <span class="progress-text">{{ process.memory }}%</span>
              </div>
            </span>
            <span class="col-status">
              <el-tag :type="process.status === 'running' ? 'success' : 'warning'" size="small">
                {{ process.statusText }}
              </el-tag>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { 
  Monitor, 
  VideoPlay, 
  Refresh,
  Top,
  Bottom,
  Minus,
  Odometer,
  Grid,
  FolderOpened,
  Connection
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const timeRange = ref('5m')
const isRealtime = ref(true)
const cpuUsage = ref(35)
const memoryUsage = ref(68)
const diskUsage = ref(45)
const networkSpeed = ref('125 MB/s')

// 趋势指示
const cpuTrend = ref('up')
const memoryTrend = ref('down')
const diskTrend = ref('stable')
const networkTrend = ref('up')

const cpuTrendIcon = ref('Top')
const memoryTrendIcon = ref('Bottom')
const diskTrendIcon = ref('Minus')
const networkTrendIcon = ref('Top')

// 图表引用
const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
let cpuChart = null
let memoryChart = null

// 进程数据
const processes = ref([
  { id: 1, name: 'electromagnetic-analyzer', cpu: 25, memory: 35, status: 'running', statusText: '运行中' },
  { id: 2, name: 'data-aggregator', cpu: 18, memory: 28, status: 'running', statusText: '运行中' },
  { id: 3, name: 'signal-processor', cpu: 15, memory: 22, status: 'running', statusText: '运行中' },
  { id: 4, name: 'spectrum-engine', cpu: 12, memory: 18, status: 'running', statusText: '运行中' },
  { id: 5, name: 'frequency-detector', cpu: 8, memory: 15, status: 'running', statusText: '运行中' },
  { id: 6, name: 'waveform-analyzer', cpu: 6, memory: 12, status: 'idle', statusText: '空闲' },
  { id: 7, name: 'data-indexer', cpu: 4, memory: 8, status: 'running', statusText: '运行中' },
  { id: 8, name: 'log-collector', cpu: 3, memory: 6, status: 'running', statusText: '运行中' },
  { id: 9, name: 'config-manager', cpu: 2, memory: 4, status: 'idle', statusText: '空闲' },
  { id: 10, name: 'health-monitor', cpu: 1, memory: 2, status: 'running', statusText: '运行中' }
])

// 图表数据
const cpuData = ref([])
const memoryData = ref([])
const timeLabels = ref([])

let updateTimer = null

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // CPU图表
  if (cpuChartRef.value) {
    cpuChart = echarts.init(cpuChartRef.value, 'dark')
    const cpuOption = {
      backgroundColor: 'transparent',
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels.value,
        axisLine: { lineStyle: { color: '#2d3a4b' } },
        axisLabel: { color: '#8591a3', fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLine: { lineStyle: { color: '#2d3a4b' } },
        axisLabel: { color: '#8591a3', fontSize: 10 },
        splitLine: { lineStyle: { color: '#2d3a4b' } }
      },
      series: [{
        data: cpuData.value,
        type: 'line',
        smooth: true,
        lineStyle: { color: '#409EFF', width: 2 },
        itemStyle: { color: '#409EFF' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }]
    }
    cpuChart.setOption(cpuOption)
  }

  // 内存图表
  if (memoryChartRef.value) {
    memoryChart = echarts.init(memoryChartRef.value, 'dark')
    const memoryOption = {
      backgroundColor: 'transparent',
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels.value,
        axisLine: { lineStyle: { color: '#2d3a4b' } },
        axisLabel: { color: '#8591a3', fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLine: { lineStyle: { color: '#2d3a4b' } },
        axisLabel: { color: '#8591a3', fontSize: 10 },
        splitLine: { lineStyle: { color: '#2d3a4b' } }
      },
      series: [{
        data: memoryData.value,
        type: 'line',
        smooth: true,
        lineStyle: { color: '#67C23A', width: 2 },
        itemStyle: { color: '#67C23A' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ]
          }
        }
      }]
    }
    memoryChart.setOption(memoryOption)
  }
}

// 更新数据
const updateData = () => {
  // 生成模拟数据
  const now = new Date()
  const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
  
  // 更新CPU和内存使用率
  cpuUsage.value = Math.max(10, Math.min(90, cpuUsage.value + (Math.random() - 0.5) * 10))
  memoryUsage.value = Math.max(10, Math.min(90, memoryUsage.value + (Math.random() - 0.5) * 8))
  
  // 更新图表数据
  cpuData.value.push(cpuUsage.value)
  memoryData.value.push(memoryUsage.value)
  timeLabels.value.push(timeStr)
  
  // 保持最近60个数据点
  if (cpuData.value.length > 60) {
    cpuData.value.shift()
    memoryData.value.shift()
    timeLabels.value.shift()
  }
  
  // 更新图表
  if (cpuChart) {
    cpuChart.setOption({
      xAxis: { data: timeLabels.value },
      series: [{ data: cpuData.value }]
    })
  }
  
  if (memoryChart) {
    memoryChart.setOption({
      xAxis: { data: timeLabels.value },
      series: [{ data: memoryData.value }]
    })
  }
}

// 切换实时监控
const toggleRealtime = () => {
  isRealtime.value = !isRealtime.value
  if (isRealtime.value) {
    startRealtime()
  } else {
    stopRealtime()
  }
}

// 开始实时监控
const startRealtime = () => {
  if (updateTimer) clearInterval(updateTimer)
  updateTimer = setInterval(updateData, 2000)
}

// 停止实时监控
const stopRealtime = () => {
  if (updateTimer) {
    clearInterval(updateTimer)
    updateTimer = null
  }
}

// 刷新进程列表
const refreshProcesses = () => {
  // 模拟刷新进程数据
  processes.value.forEach(process => {
    process.cpu = Math.max(1, Math.min(30, process.cpu + (Math.random() - 0.5) * 5))
    process.memory = Math.max(1, Math.min(40, process.memory + (Math.random() - 0.5) * 3))
  })
}

// 生命周期
onMounted(() => {
  // 初始化数据
  for (let i = 0; i < 30; i++) {
    const now = new Date(Date.now() - (30 - i) * 2000)
    const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
    timeLabels.value.push(timeStr)
    cpuData.value.push(Math.random() * 60 + 20)
    memoryData.value.push(Math.random() * 50 + 30)
  }
  
  initCharts()
  startRealtime()
})

onBeforeUnmount(() => {
  stopRealtime()
  if (cpuChart) cpuChart.dispose()
  if (memoryChart) memoryChart.dispose()
})
</script>

<style scoped>
.resource-monitor {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #263445;
  border-radius: 0.8vh;
  overflow: hidden;
}

.monitor-header {
  padding: 1.5vh 2vw;
  background: #1f2d3d;
  border-bottom: 1px solid #2d3a4b;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monitor-title {
  margin: 0;
  font-size: 1.1rem;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 0.8vw;
}

.monitor-controls {
  display: flex;
  gap: 1vw;
  align-items: center;
}

.monitor-content {
  flex: 1;
  padding: 2vh;
  display: flex;
  flex-direction: column;
  gap: 2vh;
  overflow: hidden;
}

.system-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5vw;
}

.overview-card {
  background: #1f2d3d;
  border-radius: 0.6vh;
  padding: 1.5vh;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.card-icon {
  width: 4vh;
  height: 4vh;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  color: #ffffff;
}

.card-icon.cpu { background: #409EFF; }
.card-icon.memory { background: #67C23A; }
.card-icon.disk { background: #E6A23C; }
.card-icon.network { background: #F56C6C; }

.card-info {
  flex: 1;
}

.card-value {
  font-size: 1.3rem;
  font-weight: 600;
  color: #bfcbd9;
  margin-bottom: 0.5vh;
}

.card-label {
  font-size: 0.8rem;
  color: #8591a3;
}

.card-trend {
  font-size: 1rem;
}

.card-trend.up { color: #F56C6C; }
.card-trend.down { color: #67C23A; }
.card-trend.stable { color: #8591a3; }

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2vw;
  height: 25vh;
}

.chart-panel {
  background: #1f2d3d;
  border-radius: 0.6vh;
  padding: 1.5vh;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vh;
  color: #bfcbd9;
  font-size: 0.9rem;
}

.chart-value {
  color: #409EFF;
  font-weight: 600;
}

.chart-content {
  flex: 1;
  min-height: 0;
}

.process-list {
  background: #1f2d3d;
  border-radius: 0.6vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  padding: 1.5vh 2vw;
  border-bottom: 1px solid #2d3a4b;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #bfcbd9;
  font-weight: 600;
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.process-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  gap: 1vw;
  padding: 1vh 2vw;
  background: #263445;
  color: #8591a3;
  font-size: 0.8rem;
  font-weight: 600;
}

.process-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  gap: 1vw;
  padding: 1vh 2vw;
  border-bottom: 1px solid #2d3a4b;
  color: #bfcbd9;
  font-size: 0.8rem;
}

.process-item:hover {
  background: rgba(64, 158, 255, 0.1);
}

.progress-bar {
  position: relative;
  background: #2d3a4b;
  border-radius: 1vh;
  height: 1.5vh;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #409EFF;
  border-radius: 1vh;
  transition: width 0.3s ease;
}

.progress-fill.memory {
  background: #67C23A;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.7rem;
  color: #bfcbd9;
  font-weight: 600;
}

@media (max-width: 1400px) {
  .system-overview {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
}
</style>